package com.douyu.ocean.invoke;

import com.douyu.ocean.invoke.model.PerformanceResult;

import java.util.Collection;
import java.util.List;
import java.util.Random;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Stopwatch;

import static java.util.concurrent.TimeUnit.MICROSECONDS;
import static java.util.concurrent.TimeUnit.MILLISECONDS;

/**
 * @author leiruiqi on 2018/7/30
 */
public class PerfomanceAopUtil {

    public static interface MethodHandler<T> {

        /**
         * 返回标准格式的resful api model
         * @return
         */
        T getResponse() ;
    }

    public static interface ResultHandler {

        /**
         * 返回标准格式的resful api model
         * @return
         */
        void sendLastestResult(List<PerformanceResult> result) ;
    }



    @SuppressWarnings("rawtypes")
    public static Object doHandler(MethodHandler handler, String actionName) {
        Stopwatch stopwatch = Stopwatch.createStarted();
        boolean excuteResult = true;
        try {
            Object response = handler.getResponse();
            return response;
        } catch (RuntimeException e) {
            excuteResult = false;
            throw e;
        } finally {
            //耗时收集
            stopwatch.stop();
            long micro = stopwatch.elapsed(MICROSECONDS );

            PerformanceCollectUtil.saveRecord(actionName,micro,excuteResult);
        }
    }

    @SuppressWarnings("rawtypes")
    public static Object doHandler(MethodHandler handler, String actionName,double boost,boolean throwe) {

        if(!PerformanceCore.needInvoke(PerformanceCore.getInvokeRateByName(actionName),boost)){
            return null;
        }
        Stopwatch stopwatch = Stopwatch.createStarted();
        boolean excuteResult = true;
        try {
            Object response = handler.getResponse();
            return response;
        } catch (RuntimeException e) {
            excuteResult = false;
            if(throwe){
                throw e;
            }else{
                return null;
            }

        } finally {
            //耗时收集
            stopwatch.stop();
            long micro = stopwatch.elapsed(MICROSECONDS);
            PerformanceCollectUtil.saveRecord(actionName,micro,excuteResult);
        }
    }


}
